package com.ityuwen.mengyagushi.live.api;

import com.alibaba.fastjson.JSON;
import com.ityuwen.mengyagushi.common.constant.RedisConstant;
import com.ityuwen.mengyagushi.live.config.ChartRoomContainer;
import com.ityuwen.mengyagushi.model.live.FromUser;
import com.ityuwen.mengyagushi.model.live.SocketMsg;
import com.ityuwen.mengyagushi.vo.user.UserInfoVo;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

@Controller
@ServerEndpoint("/api/websocket/{liveRoomId}/{token}")
public class WebSocketController {

    //@Autowired  // 多例模式 直接autowired
    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        WebSocketController.redisTemplate = redisTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("liveRoomId")Long liveRoomId, @PathParam("token")String token){
        System.out.println("建立连接！" + liveRoomId + "====" + token);

        // 根据token获取当前登录用户的信息
        UserInfoVo userInfoVo = (UserInfoVo)this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        ChartRoomContainer.addUser(liveRoomId, userInfoVo.getId(), session);

        SocketMsg msg = new SocketMsg();
        msg.setMsgContent(userInfoVo.getNickname() + "加入了直播间");
        msg.setMsgType(SocketMsg.MsgTypeEnum.JOIN_CHAT.getCode());
        msg.setLiveRoomId(liveRoomId);
        msg.setTime(LocalDateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        // 发送用户
        FromUser fromUser = new FromUser();
        fromUser.setUserId(userInfoVo.getId());
        fromUser.setNickname(userInfoVo.getNickname());
        fromUser.setAvatarUrl(userInfoVo.getAvatarUrl());
        msg.setFromUser(fromUser);
//        ChartRoomContainer.sendMsg(JSON.toJSONString(msg));
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL, JSON.toJSONString(msg));
    }

    @OnClose
    public void onClose(Session session, @PathParam("liveRoomId")Long liveRoomId, @PathParam("token")String token){
        System.out.println("关闭连接！" + liveRoomId + "====" + token);
        UserInfoVo userInfoVo = (UserInfoVo)this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        ChartRoomContainer.removeUser(liveRoomId, userInfoVo.getId());

        SocketMsg msg = new SocketMsg();
        msg.setMsgContent(userInfoVo.getNickname() + "离开了直播间");
        msg.setMsgType(SocketMsg.MsgTypeEnum.CLOSE_SOCKET.getCode());
        msg.setLiveRoomId(liveRoomId);
        msg.setTime(LocalDateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        // 发送用户
        FromUser fromUser = new FromUser();
        fromUser.setUserId(userInfoVo.getId());
        fromUser.setNickname(userInfoVo.getNickname());
        fromUser.setAvatarUrl(userInfoVo.getAvatarUrl());
        msg.setFromUser(fromUser);
//        ChartRoomContainer.sendMsg(JSON.toJSONString(msg));
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL, JSON.toJSONString(msg));
    }

    @OnMessage
    public void onMessage(Session session, String msg){
        System.out.println("获取了消息：" + msg);

//        ChartRoomContainer.sendMsg(msg);
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL, msg);
    }

    @OnError
    public void onError(Session session, Throwable ex){
        System.out.println("连接出错：" + ex.getMessage());
    }
}
